package com.example.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.util.BeanUtils;
import com.diboot.iam.entity.BaseLoginUser;
import com.diboot.iam.util.IamSecurityUtils;
import com.example.demo.dto.ProductionOrderItemTaskDTO;
import com.example.demo.dto.ProductionOrderTaskDTO;
import com.example.demo.entity.ProcurementOrderItem;
import org.springframework.ui.ModelMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.example.demo.entity.ProductionOrder;
import com.example.demo.dto.ProductionOrderDTO;
import com.example.demo.vo.ProductionOrderListVO;
import com.example.demo.vo.ProductionOrderDetailVO;
import com.example.demo.service.ProductionOrderService;
import com.example.demo.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;

/**
 * 生产单 相关Controller
 *
 * @author MyName
 * @version 1.0
 * @date 2024-02-26
 * Copyright © MyCompany
 */
@RestController
@RequestMapping("/productionOrder")
@BindPermission(name = "生产单")
@Slf4j
public class ProductionOrderController extends BaseCustomCrudRestController<ProductionOrder> {

    @Autowired
    private ProductionOrderService productionOrderService;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult<List<ProductionOrderListVO>> getViewObjectListMapping(ProductionOrderDTO queryDto, Pagination pagination) throws Exception {
        return super.getViewObjectList(queryDto, pagination, ProductionOrderListVO.class);
    }

    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/userlist")
    public JsonResult<List<ProductionOrderListVO>> userlist(ProductionOrderDTO queryDto, Pagination pagination) throws Exception {
      BaseLoginUser currentUser = IamSecurityUtils.getCurrentUser();
      queryDto.setIamUserId(currentUser.getId());
      return super.getViewObjectList(queryDto, pagination, ProductionOrderListVO.class);
    }

    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/all")
    public JsonResult<List<ProductionOrderListVO>> getAllViewObjectListMapping(ProductionOrderDTO queryDto) throws Exception {
        BaseLoginUser currentUser = IamSecurityUtils.getCurrentUser();
        queryDto.setIamUserId(currentUser.getId());
        Pagination pagination = new Pagination();
        pagination.setPageIndex(1);
        pagination.setPageSize(1000);
        return super.getViewObjectList(queryDto, pagination, ProductionOrderListVO.class);
    }

    /**
     * 查询树ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/treeList")
    public JsonResult<List<ProductionOrderListVO>> getViewObjectTreeListMapping(ProductionOrderDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<ProductionOrder> queryWrapper = super.buildQueryWrapperByQueryParams(queryDto);
        List<ProductionOrderListVO> voList = productionOrderService.getViewObjectList(queryWrapper, null, ProductionOrderListVO.class);
        if (queryWrapper.isEmptyOfNormal()) {
            voList = BeanUtils.buildTree(voList);
        }
        return JsonResult.OK(voList);
    }

    /**
     * 获取树结构数据接口
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/tree")
    public JsonResult<List<ProductionOrderDetailVO>> getRootNodeTree() throws Exception {
        List<ProductionOrderDetailVO> productionOrderVOList = productionOrderService.getProductionOrderTree(0L);
        return JsonResult.OK(productionOrderVOList);
    }

    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, ProductionOrderDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult<?> createEntityMapping(@Valid @RequestBody ProductionOrderTaskDTO productionOrderTaskDTO) throws Exception {
        List<ProductionOrder> productionOrderList = new ArrayList<>();
        for (ProductionOrderItemTaskDTO productionOrderItemTaskDTO : productionOrderTaskDTO.getMultipleSelection()) {
            ProductionOrder entity = new ProductionOrder();
            entity.setTitle(productionOrderTaskDTO.getTitle());
            entity.setOrdersId(productionOrderTaskDTO.getOrdersId());
            entity.setOrderSkuId(productionOrderItemTaskDTO.getId());
            entity.setQuantity(productionOrderItemTaskDTO.getUsequantity());
            entity.setIamUserId(productionOrderTaskDTO.getIamUserId());
            productionOrderList.add(entity);
        }
        return JsonResult.OK(productionOrderService.createEntities(productionOrderList));
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody ProductionOrder entity) throws Exception {
        return super.updateEntity(id, entity);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * 删除对象前的操作
     *
     * @param entityOrDto
     * @return
     * @throws Exception
     */
    protected String beforeDelete(ProductionOrder entityOrDto) throws Exception {
        // 判断是否具有叶子节点（仅允许没有叶子节点的节点进行删除操作）
        LambdaQueryWrapper<ProductionOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductionOrder::getParentId, entityOrDto.getPrimaryKeyVal());
        Long count = productionOrderService.getEntityListCount(wrapper);
        if (count > 0) {
            return "请先删除当前节点下的所有下级节点再重试";
        }
        return null;
    }
}
